package com.yuneec.droneservice.command;

import com.MAVLink.yuneec.msg_mav_rc_cmd_ack;
import com.yuneec.droneservice.model.PackageInfo;
import com.yuneec.droneservice.request.IResponse;

import java.nio.charset.Charset;

/**
 * Created by gjw on 2017/3/27.
 */

public class StartUpdate extends BaseCommand {
    private final PackageInfo packageInfo;

    public StartUpdate(PackageInfo packageInfo) {
        super(MAV_RC_COMMAND.MAV_RC_CMD_START_UPDATE);
        this.packageInfo = packageInfo;
    }

    @Override
    protected short[] body() {
        Charset utf = Charset.forName("utf8");
        byte[] hardwareVersion = packageInfo.getHardwareVersion().getBytes(utf);
        byte[] firmwareVersion = packageInfo.getFirmwareVersion().getBytes(utf);
        byte[] mcuVersion = packageInfo.getMcuVersion().getBytes(utf);
        byte[] fileName = packageInfo.getFilename().getBytes(utf);
        byte[] type = packageInfo.getType().getBytes(utf);
        short[] data = new short[hardwareVersion.length + firmwareVersion.length + mcuVersion.length + fileName.length + type.length + 14];
        int index = 0;
        shortToUIntArray(data, index, (short) hardwareVersion.length);
        index += 2;
        byteArrayToUIntArray(data, index, hardwareVersion, 0);
        index += hardwareVersion.length;

        shortToUIntArray(data, index, (short) firmwareVersion.length);
        index += 2;
        byteArrayToUIntArray(data, index, firmwareVersion, 0);
        index += firmwareVersion.length;

        shortToUIntArray(data, index, (short) mcuVersion.length);
        index += 2;
        byteArrayToUIntArray(data, index, mcuVersion, 0);
        index += mcuVersion.length;

        shortToUIntArray(data, index, (short) fileName.length);
        index += 2;
        byteArrayToUIntArray(data, index, fileName, 0);
        index += fileName.length;


        intToUIntArray(data, index, (int) packageInfo.getFileSize());
        index += 4;

        shortToUIntArray(data, index, (short) type.length);
        index += 2;
        byteArrayToUIntArray(data, index, type, 0);
        index += type.length;


        return data;
    }

    @Override
    public IResponse toResponse(msg_mav_rc_cmd_ack ack) {
        int code = ack.code;
        return new IResponse(ids(), code);
    }
}
